package com.cheng.io.demo;

import java.io.*;

public class FolderCopy {

    public static void main(String[] args) {
        File oldFolder = new File("io/resources");
        File newFolder = new File("D:/test");

        copy(oldFolder, newFolder, null);
    }

    /**
     * @param oldFolder 原始目录
     * @param newFolder 目标目录
     * @param pathname 递归使用，对外无效
     */
    private static void copy(File oldFolder, File newFolder, String pathname) {
        // 对文件进行复制操作
        if (oldFolder.isFile()) {
            try (
                    InputStream inputStream = new FileInputStream(oldFolder);
                    OutputStream outputStream = new FileOutputStream(pathname + File.separator + oldFolder.getName());
            ) {
                // 每次读写1MB
                byte[] bytes = new byte[1024 * 1024];
                int readCount;
                while ((readCount = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, readCount);
                }
                outputStream.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }

        // 拼接路径（目标路径 + 原路径的指定目录嵌套路径）
        pathname = newFolder.getAbsolutePath() + File.separator + oldFolder.getPath().substring(3);
        File createFolder = new File(pathname);
        // 创建多级目录
        if (!createFolder.exists()) createFolder.mkdirs();
        // 遍历目录中的元素
        File[] files = oldFolder.listFiles();
        for (File file : files) {
            // 递归目录
            copy(file, newFolder, pathname);
        }
    }
}
